package com.example.config.redisandlua;

import com.google.common.collect.Lists;
import common.annotations.Inner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

/**
 * @Author Story
 * @Date 2022/3/20 5:17
 * @Version 1.0
 */
@Slf4j
@Component
public class AccessLimiter {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired(required = false)
    private RedisScript<Boolean> rateLimitLua;

    /**
     * @param key
     * @param limit rateLimitLua==lua脚本的真身
     *              Lists.newArrayList(key)==lua脚本中的key列表
     *              limit.toString()==lua脚本的value列表
     */
    @Inner
    public void limitAccess(String key, Integer limit) {
        boolean acquired = stringRedisTemplate.execute(
                rateLimitLua,
                Lists.newArrayList(key),
                limit.toString()
        );

        if (!acquired) {
            log.error("Your access is blocked,key={}", key);
            throw new RuntimeException("Your access is blocked");
        }
    }

}
